package com.easyj.admin.sys.controller;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.easyj.base.common.ajax.Result;
import com.easyj.base.common.imp.ImpUtils;
import com.easyj.base.common.vo.tree.TreeNode;
import com.easyj.base.controller.BaseController;
import com.easyj.base.exception.ValidateException;
import com.easyj.base.security.service.SecurityUtil;
import com.easyj.base.util.DateTimeUtil;
import com.easyj.admin.db.model.Department;
import com.easyj.admin.db.model.ImpResult;
import com.easyj.admin.sys.service.DepartmentService;
	/**
	* 部门
	*
	 */
	@RestController
	@RequestMapping(value = "/sys/department")
	public class DepartmentController extends BaseController{

		@Autowired
		private  DepartmentService departmentService;

		/**
		 * get
		 * @param id
		 * @return
		 */
	    @GetMapping("/{id}")
	    public Result get(@PathVariable("id") Long id) {
	        Department entity = departmentService.findById(id);
	        if(entity!=null && entity.getParentId().longValue()!=0) {
	        	Department parent=departmentService.findById(entity.getParentId());
	        	entity.setParent(parent);	        	
	        }
	        return Result.Success(entity);
	    }
		
		/**
		* 新增
		 * @throws ValidateException 
		*/
	    @PreAuthorize("hasPermission('department','department:all')")
		@RequestMapping(value = "add", method = RequestMethod.POST)
		public Result add(@RequestBody @Validated Department entity,BindingResult validResult) throws ValidateException {
			if(entity.getParentId()==null||validResult.hasErrors()){
				return Result.Error("新增错误,数据不符合要求！");  
			}
				
			entity.setOperatorId(SecurityUtil.getOperatorId());	
			departmentService.insertEntity(entity);
			return Result.Success();
			
		}
		
		/**
		* 修改
		 * @throws ValidateException 
		*/
	    @PreAuthorize("hasPermission('department','department:all')")
		@RequestMapping(value = "update", method = RequestMethod.POST)
		public Result update(@RequestBody @Validated Department entity,BindingResult validResult) throws ValidateException {
			if(validResult.hasErrors()){
				return Result.Error("修改错误,数据不符合要求！");  
			}
		
			entity.setOperatorId(SecurityUtil.getOperatorId());	
			departmentService.updateEntity(entity);
			return Result.Success();
			
		}
	    
	    
	    
	    @PreAuthorize("hasPermission('department','department:all')")
		@RequestMapping(value = "changeParent", method = RequestMethod.POST)
		public Result changeParent(Long id,Long parentId) throws ValidateException {
			if(id==null){
				return Result.Error("数据不符合要求！");  
			}
				
			departmentService.changeParent(id,parentId,SecurityUtil.getOperatorId());
			return Result.Success();
			
		}
	    
	    
	    
	    
		/**
		* 查询
		* @param filter
		* @return
		 */
		@RequestMapping(value = "findList", method = RequestMethod.POST)
		public Result findList(@RequestBody  Department filter) {
			List<Department>  list =departmentService.findList(filter);
			return Result.Success(list);
			
		}
		
		
		@RequestMapping(value = "getTree", method= {RequestMethod.POST,RequestMethod.GET})
		public Result getTree() {			
			List<TreeNode>  list =departmentService.getTree(false);
			return Result.Success(list);
			
		}
		
		@RequestMapping(value = "getCompanyTree", method= {RequestMethod.POST,RequestMethod.GET})
		public Result getCompanyTree() {			
			List<TreeNode>  list =departmentService.getTree(true);
			return Result.Success(list);
			
		}
		
		@RequestMapping(value = "getAllTree", method= {RequestMethod.POST,RequestMethod.GET})
		public Result getAllTree() {			
			List<TreeNode>  list =departmentService.getAllTree();
			return Result.Success(list);
			
		}
		
        /**
 		 *删除，为了防止误删相关的表要做外键关联
 		*/
		@PreAuthorize("hasPermission('department','department:all')")
 		@RequestMapping(value = "delete", method = {RequestMethod.POST,RequestMethod.GET})
 		public Result delete(@RequestParam(value = "id") Long id){
 			try{
 				//check ------
 				//Department dept=departmentService.findById(id);
 				//if(dept.getParentId().longValue()==0) {
 				//	return Result.Error("一级部门不可删除！"); 
 				//}
 				Department filter=new Department();
 				filter.setParentId(id);
 				List<Department> list=departmentService.findList(filter);
 				if(list!=null && list.size()>0) {
 					return Result.Error("所选部门有下级部门不可删除！需先删除下级部门。"); 
 				}
 				//check user?
 				Long userId=SecurityUtil.getOperatorId();
 				departmentService.deleteById(id,userId	);
 				return Result.Success();
 			}catch(Exception ex){
 				log.error("DepartmentController.delete", ex);
				return Result.Error("删除部门错误！部门已使用。"); 
 			}
 			
 		}
		
		@PreAuthorize("hasPermission('department','department:all')")
 		@RequestMapping(value = "changeStatus", method = RequestMethod.POST)
 		public Result changeStatus(@RequestParam(value = "id") Long id){
			//check ------
			Department dept=departmentService.findById(id);
			//if(dept.getParentId().longValue()==0) {
			//	return Result.Error("一级部门不可停用！"); 
			//}
			
			//check user?
			Long userId=SecurityUtil.getOperatorId();
			if(dept.getDeleted()) {
			  departmentService.enableById(id,userId	);
			}else {
				departmentService.disabledById(id,userId	);
			}
			return Result.Success();
 			
 			
 		}
		

		/**
		  *  下载导入模板
		 * @param response
		 */
		@PreAuthorize("hasPermission('department','department:all')")
		@RequestMapping(value = "exportTpl", method = RequestMethod.GET)
		public void exportTpl( HttpServletResponse response){
			try {
				//生成 excel
				SXSSFWorkbook workbook=ImpUtils.getImpTemplateExcel("department.xml","");
				response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 
				String filename="组织架构导入模板"+DateTimeUtil.getDateStr8(new Date())+".xlsx";
				String newFileName=URLEncoder.encode(filename,"UTF-8");
				response.setHeader("Content-disposition", "attachment;filename=" + newFileName); 
				OutputStream ouputStream = response.getOutputStream();  
				workbook.write(ouputStream);  
				ouputStream.flush();  
				ouputStream.close();  
			}catch (Exception ex) {
				log.error("DepartmentController.exportTpl", ex);
			} 
		}		
		
		/**
		 * 导入
		 * 配合element upload 控件
	            * 直接  throw error
		 * @param file
		 * @return
		 * @throws Exception
		 */
		@PreAuthorize("hasPermission('department','department:all')")
		@RequestMapping(value = "importExcel", method = RequestMethod.POST)
		public Result importExcel(@RequestParam MultipartFile file) throws Exception{
			ImpResult rtn=departmentService.importExcel(file, SecurityUtil.getOperatorId());
			return Result.Success(rtn);
		}
		
}

